﻿using System;
using Hopscotch.Common.Logging;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.Practices.Unity;

namespace Hopscotch.Server.EnqSignalRHost
{
	/// <summary>
	/// The UnityHubActivator class is used by SignalR to resolved Hub instances using Unity
	/// </summary>
	/// <remarks>It is important that the Hub is created using the transient lifecycle manager from Unity.
	/// See signalr docs: Hub object lifetime </remarks>
	public class UnityHubActivator : IHubActivator
	{
		static readonly ILogger logger = AppLogger.CreateLogger<UnityHubActivator>();

		private readonly IUnityContainer container;

		public UnityHubActivator(IUnityContainer container)
		{
			this.container = container;
		}

		public IHub Create(HubDescriptor descriptor)
		{
			if (descriptor == null)
			{
				throw new ArgumentNullException("descriptor");
			}

			if (descriptor.HubType == null)
			{
				return null;
			}

			logger.Debug("Creating Hub {0}", descriptor.HubType);
			object hub = container.Resolve(descriptor.HubType) ?? Activator.CreateInstance(descriptor.HubType);
			return hub as IHub;
		}
	}
}
